package com.dp.service.impl3;

import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import javax.persistence.Query;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.dp.pojo.JsonPage;
import com.dp.pojo.NewsAdsVo;
import com.dp.pub.SysProperty;
import com.dp.util.BaseBean;
import com.dp.util.BookConfig;
import com.dp.util.DataMap;
import com.dp.util.InterUtil;
import com.dp.vo.NewsAds;
import com.dp.vo.NewsResources;

/**
 * 
 * 项目名称：platform_p2
 * 类名称：AdServiceImpl
 * 类描述：
 * 创建人：Administrator
 * 创建时间：Sep 2, 2009 8:29:47 PM
 * 修改人：Administrator
 * 修改时间：Sep 2, 2009 8:29:47 PM
 * 修改备注：
 * @version 
 * 
 */
@Service
@Transactional
public class AdServiceImpl3 extends BaseImpl {

	public int findAllAdsContentCount(DataMap hashMap) {
		String roleid = (String)hashMap.get("roleid");
		String userid = (String)hashMap.get("userid");
		String userids=(String)hashMap.get("userids");
		String adtitle = (String)hashMap.get("adtitle");
		String ader = (String)hashMap.get("ader");
		String status = (String)hashMap.get("status");
		String channelid = (String)hashMap.get("channelid");
		String begintime = (String)hashMap.get("begintime");
		String endtime = (String)hashMap.get("endtime");
		int adtype = (Integer)hashMap.get("adtype");
		String sql = "SELECT count(ads.adid) FROM news_ads as ads ";
		if (channelid != null && !"".equals(channelid)) {
			sql += ",news_contenttitle nc,news_extends_channel_title nect,news_extends_channel nec where ";
			sql += "ads.adtype= "+adtype+" and nec.channel_id='"+channelid+"' and nc.contentid=ads.adid and nc.cid=nect.cid and nect.channleid=nec.channleid";

		}else{
			sql += "where ads.adtype= "+adtype;
		}
		//权限
		if(StringIsNotNull(roleid) && StringIsNotNull(userid))
		{
			sql = sql + " AND ads.adorder='" + userid + "'";
		}else if(userids!=null){
			sql = sql + " AND ads.adorder in (" + userids + ")";
		}
		if (adtitle != null && !"".equals(adtitle)) {
			sql += " and ads.adtitle like '%" + adtitle + "%'";
		}
		if (ader != null && !"".equals(ader)) {
			sql += " and ads.ader = '" + ader + "'";
		}
		if(status != null && !"".equals(status)) {
//			if(status.contains("|"))
//			{
//				String auditing = status.substring(0,status.indexOf("|"));
//				String newStatus = status.substring(status.indexOf("|")+1);
//				sql += " and (tp.content_status = '"+ auditing +"' or tp.content_status = '"+newStatus+"')";
//			}
//			else
			sql += " and ads.adstatus = '" + status + "'";
		}
		if(null != begintime && !begintime.equals("")){
			sql += " and ads.begintime >= '" + begintime + "'";
		}
		if(null != endtime && !endtime.equals("")){
			sql += " and ads.endtime <= '" + endtime + "'";
		}
		String count = "0";
		try {
			log.info(" findAllPictureContentCount excute sql: " +sql);
			count = this.queryOne(sql);
		} catch (Exception e) {
			log.info(" findAllPictureContentCount fail !!!" +e.getMessage());
			e.printStackTrace();
		}
		return Integer.parseInt(count);
	}

	//新UI分页查询（频道、分类广告）
	public List<NewsAdsVo> findAllAdsContent(DataMap hashMap, int firstrow, int maxrow) {
		JsonPage jpage=(JsonPage)hashMap.get("jpage");
		String roleid = (String)hashMap.get("roleid");
		String userid = (String)hashMap.get("userid");
		String userids=(String)hashMap.get("userids");
		String adtitle = (String)hashMap.get("adtitle");
		String ader = (String)hashMap.get("ader");
		String status = (String)hashMap.get("status");
		String channelid = (String)hashMap.get("channelid");
		String begintime = (String)hashMap.get("begintime");
		String endtime = (String)hashMap.get("endtime");
		int adtype = (Integer)hashMap.get("adtype");
		String sql = "SELECT ads.adid,ads.adtitle,ads.adtext,ads.adpictureid,ads.adurl,ads.adstandtime,ads.adorder,ads.ader,ads.createtime,ads.endtime,ads.begintime,ads.note,ads.adtype,ads.adstatus,ads.position FROM news_ads as ads ";
		if (channelid != null && !"".equals(channelid)) {
			sql += ",news_contenttitle nc,news_extends_channel_title nect,news_extends_channel nec where";
			sql += " nec.channel_id='"+channelid+"' and nc.contentid=ads.adid and nc.cid=nect.cid and nect.channleid=nec.channleid";
		}else{
			sql += " where 1 =1 ";
		}
		//权限
		if(StringIsNotNull(roleid) && StringIsNotNull(userid))
		{
			sql = sql + " AND ads.adorder='" + userid + "'";
		}else if(userids!=null){
			sql = sql + " AND ads.adorder in (" + userids + ")";
		}
		if (adtitle != null && !"".equals(adtitle)) {
			sql += " and ads.adtitle like '%" + adtitle + "%'";
		}
		if (ader != null && !"".equals(ader)) {
			sql += " and ads.ader = '" + ader + "'";
		}
		if(status != null && !"".equals(status)) {
			sql += " and ads.adstatus = '" + status + "'";
		}
		if(null != begintime && !begintime.equals("")){
			sql += " and ads.begintime >= '" + begintime + "'";
		}
		if(null != endtime && !endtime.equals("")){
			sql += " and ads.endtime <= '" + endtime + "'";
		}
		sql += " and ads.adtype="+adtype;
		if (jpage != null && jpage.getSidx() != null
				&& !"".equals(jpage.getSidx())) {
			sql += " order by ads." + jpage.getSidx();
			sql += " " + jpage.getSord();
		}
		log.info(" findAll Ads Content excute sql: " +sql);
		List<Object[]> list = this.getNativeQuery(sql, firstrow, maxrow);
		List<NewsAdsVo> result = null;
		try {
			if (list.size() > 0) 
			{
				result = new ArrayList<NewsAdsVo>(list.size());
				
				for (Object[] objects : list) 
				{
					if (objects != null && objects.length > 0) 
					{
						int j = 0;
						NewsAdsVo one = new NewsAdsVo();
						one.setAdid((Integer)objects[j++]);
						one.setAdtitle((String)objects[j++]);
						one.setAdtext((String)objects[j++]);
						one.setAdpictureid((Integer)objects[j++]);
						one.setAdurl((String)objects[j++]);
						one.setAdstandtime((Integer)objects[j++]);
						one.setAdorder((String)objects[j++]);
						one.setAder((String)objects[j++]);
						one.setCreatetime((Date) objects[j++]);
						one.setEndtime((Date) objects[j++]);
						one.setBegintime((Date) objects[j++]);
						one.setNote((String)objects[j++]);
						one.setAdtype((Integer)objects[j++]);
						one.setAdstatus((String)objects[j++]);
						one.setPosition((Integer)objects[j++]);
						result.add(one);
					}
				}
			}
			return result;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
	
	/*@SuppressWarnings("unchecked")
	public List<NewsAds> findAllAd(String buttontxt,String buttontype) {
		String hql = "SELECT a FROM NewsAds a";
		return getQueryList(hql);
	}*/
	
	public NewsAdsVo findAdVoById(Integer adid)
	{
		NewsAdsVo tmp = null;
		this.sql = "SELECT ads.adid,ads.adtitle,ads.adtext,ads.adpictureid,ads.adurl,ads.adstandtime,ads.adorder,ads.ader,ads.createtime,ads.endtime,ads.begintime,ads.note,ads.adtype,ads.adstatus,ads.position,nc.contentsource,nc.allow_scoring FROM news_ads as ads";
			sql+=",news_contenttitle nc where nc.contentid=ads.adid and nc.newstype='ad' and adid=:adid" ;
		try {
			Query query = em.createNativeQuery(sql);
			query.setParameter("adid", adid);
			List<Object[]> list=query.getResultList();
			if(list.size()>0)
			{
				Object[] objects=list.get(0);
				tmp = new NewsAdsVo();
				int j=0;
				tmp.setAdid((Integer)objects[j++]);
				tmp.setAdtitle((String)objects[j++]);
				tmp.setAdtext((String)objects[j++]);
				tmp.setAdpictureid((Integer)objects[j++]);
				tmp.setAdurl((String)objects[j++]);
				tmp.setAdstandtime((Integer)objects[j++]);
				tmp.setAdorder((String)objects[j++]);
				tmp.setAder((String)objects[j++]);
				tmp.setCreatetime((Date) objects[j++]);
				tmp.setEndtime((Date) objects[j++]);
				tmp.setBegintime((Date) objects[j++]);
				tmp.setNote((String)objects[j++]);
				tmp.setAdtype((Integer)objects[j++]);
				tmp.setAdstatus((String)objects[j++]);
				tmp.setPosition((Integer)objects[j++]);
				tmp.setPhone((String)objects[j++]);
				tmp.setIsCallNow((Integer)objects[j++]);
			}
		} catch (Exception e) {
			log.error(" findAdVoById fail !!!" +e.getMessage());
			e.printStackTrace();
		}
		return tmp;
	}
	
	public NewsAds findAdById(Integer adid)
	{
		String hql = "SELECT a FROM NewsAds a where 1=1 ";
		if (adid != null && adid != 0) {
			hql += " and a.adid = " + adid ;
		}
		return (NewsAds) getSingleResult(hql);
	}
	
	/*public List<NewsAds> findAd(String adtext, String ader,	int firstrow, int maxrow) 
	{
		String hql = "SELECT a FROM NewsAds a where 1=1 ";
		if (adtext != null && !"".equals(adtext)) {
			hql += " and a.adtext like '%" + adtext + "%'";
		}
		if (ader != null && !"".equals(ader)) {
			hql += " and a.ader like '%" + ader + "%'";
		}
		hql += " order by a.createtime desc";
		return getQueryList(hql, firstrow, maxrow);
	}*/
	
	/*public Long findAdCount(String adtext, String ader) 
	{
		String hql = "SELECT count(a) FROM NewsAds a where 1=1 ";
		if (adtext != null && !"".equals(adtext)) {
			hql += " and a.adtext like '%" + adtext + "%'";
		}
		if (ader != null && !"".equals(ader)) {
			hql += " and a.ader like '%" + ader + "%'";
		}
		Object obj = getSingleResult(hql);
		if(obj ==null ){
			return Long.valueOf(0+"");
		}else{
			return (Long) obj;
		}
	}*/
	
	/*public List<NewsAds> findAdByUser(String adtext, String ader,int firstrow, int maxrow,Object userId) 
	{
		String hql = "SELECT a FROM NewsAds a where 1=1 ";
		if (adtext != null && !"".equals(adtext)) {
			hql += " and a.adtext like '%" + adtext + "%'";
		}
		if (ader != null && !"".equals(ader)) {
			hql += " and a.ader like '%" + ader + "%'";
		}
		hql += " and adorder = '" + userId + "'";
		hql += " order by a.createtime desc";
		return getQueryList(hql, firstrow, maxrow);
	}*/
	
//	public Long findAdByUserCount(String adtext, String ader,Object userId) 
//	{
//		String hql = "SELECT count(a) FROM NewsAds a where adtype=1 ";
//		if (adtext != null && !"".equals(adtext)) {
//			hql += " and a.adtext like '%" + adtext + "%'";
//		}
//		if (ader != null && !"".equals(ader)) {
//			hql += " and a.ader like '%" + ader + "%'";
//		}
//		hql += " and adorder = '" + userId + "'";
//		Object obj = getSingleResult(hql);
//		if(obj ==null ){
//			return Long.valueOf(0+"");
//		}else{
//			return (Long) obj;
//		}
//	}
	
	public Integer findPicidByFilename(String filename)
	{
		String hql = "SELECT a.rid FROM NewsResources a where 1=1 ";
		if (filename != null && !"".equals(filename)) {
			hql += " and a.url = '" + filename + "'";
		}
		Object obj = getSingleResult(hql);
		return (Integer)(obj);
	}
	public NewsResources findPicById(Integer rid)
	{
		String hql = "SELECT a FROM NewsResources a where 1=1 ";
		if (rid != null && rid != 0) {
			hql += " and a.rid = " + rid ;
		}
		Object obj = getSingleResult(hql);
		if(obj == null ){
			return null;
		}else{
			return (NewsResources)obj;
		}
	}

	public ArrayList<DataMap> findAllLastChannel(DataMap hashMap) {
		Object roleId = hashMap.get("role_id");
		Object userId = hashMap.get("user_id");
		String userids = (String)hashMap.get("userids");
		//root
		String findSql = "select  ch.channel_id  ,ch.service_code,ch.channel_name,ch.channel_comment ,ch.function_name,ch.STATUS ,ch.ordered ,ch.created_date" +
				",ch.previous_id ,ch.primal_id ,ch.LEVEL ,ch.channel_type  ,ch.channel_hot_topics ,ch.channel_classifying_label" +"  from t_channels ch WHERE 1=1 " +
				//will open
				" and status='"+BookConfig.channel_status_enable+"'" +
				" and (channel_type='"+BookConfig.channel_type_ad+"' or channel_type='"+BookConfig.channel_type_scrollbar+"' or channel_type='"+BookConfig.channel_type_hdnews+"') " +	//广告和滚动新闻类型和分类信息 
				" AND (function_name='"+BookConfig.channel_last+"' OR function_name='"+BookConfig.channel_song+"') ";
		//normal user
		if(roleId != null && !roleId.equals(""))
		{
			findSql = "select  ch.channel_id  ,ch.service_code,ch.channel_name,ch.channel_comment ,ch.function_name,ch.STATUS ,ch.ordered ,ch.created_date" +
				",ch.previous_id ,ch.primal_id ,ch.LEVEL ,ch.channel_type  ,ch.channel_hot_topics ,ch.channel_classifying_label" +"  from t_channels ch,t_user_channels uc WHERE ch.channel_id=uc.channel_id " +
		    		" and status='"+BookConfig.channel_status_enable+"'" +
					" and (channel_type='"+BookConfig.channel_type_ad+"' or channel_type='"+BookConfig.channel_type_scrollbar+"' or channel_type='"+BookConfig.channel_type_hdnews+"') " + 
		    		" and (function_name='"+BookConfig.channel_last+"' OR function_name='"+BookConfig.channel_song+"')  " +
		    		" and uc.employee_id=(SELECT employee_id FROM t_user where user_id='" + userId + "')";
		}else if(userids!=null){
			//
			findSql = "select DISTINCT  ch.channel_id  ,ch.service_code,ch.channel_name,ch.channel_comment ,ch.function_name,ch.STATUS ,ch.ordered ,ch.created_date" +
				",ch.previous_id ,ch.primal_id ,ch.LEVEL ,ch.channel_type  ,ch.channel_hot_topics ,ch.channel_classifying_label" +"  from t_channels ch,t_user_channels uc WHERE ch.channel_id=uc.channel_id " +
	    		" and status='"+BookConfig.channel_status_enable+"'" +
				" and (channel_type='"+BookConfig.channel_type_ad+"' or channel_type='"+BookConfig.channel_type_scrollbar+"' or channel_type='"+BookConfig.channel_type_hdnews+"') " + 
	    		" and (function_name='"+BookConfig.channel_last+"' OR function_name='"+BookConfig.channel_song+"')  " +
	    		" and uc.employee_id in (SELECT employee_id FROM t_user where user_id in (" + userids + "))";
		}
		try {
			return null;
			//return this.queryALLResultSet(findSql.toString());
		} catch (Exception e) {
			logger.error(" findAllLastChannel fail !!!" +e.getMessage());
			return null;
		}
	}
	
	public boolean insertAds(NewsAdsVo one,String channelids)
	{
		BaseBean b = new BaseBean();
		ArrayList<String> sqllist = new ArrayList<String>();
		String contentid = b.ObjectToStringDB(one.getAdid());
		String order = b.ObjectToStringDB(one.getAdorder());
		String content_name = b.ObjectToStringDB(one.getAdtitle());
		String content_detail = b.ObjectToStringDB(one.getAdtext());
		String pic_id = b.ObjectToStringDB(one.getAdpictureid());
		String content_pubdate = b.ObjectToStringDB(one.getBegintime());
		String deadline = b.ObjectToStringDB(one.getEndtime());
		String url = b.ObjectToStringDB(one.getAdurl()); 
		String standtime = b.ObjectToStringDB(one.getAdstandtime()); 
		String status = b.ObjectToStringDB(one.getAdstatus()); 
		String type = b.ObjectToStringDB(one.getAdtype()); 
		String ader = b.ObjectToStringDB(one.getAder()); 
		String note = b.ObjectToStringDB(one.getNote()); 
		String phone = b.ObjectToStringDB(one.getPhone()); 
		StringBuffer inPicSql = new StringBuffer("");
//		inPicSql.append(content_name+",");
//		inPicSql.append(pic_id+",");
//		inPicSql.append(url+",");
//		inPicSql.append(standtime+",");
//		inPicSql.append(order+",");
//		inPicSql.append(ader+",");
//		inPicSql.append("now(),");
//		inPicSql.append(deadline+",");
//		inPicSql.append(content_pubdate+",");
//		inPicSql.append(note+",");
//		inPicSql.append(type+",");
//		inPicSql.append("'new')");
//		sqllist.add(inPicSql.toString());
//		log.info(" insertPicture excute batch sql 1:" +inPicSql.toString());
//		inPicSql.delete(0, inPicSql.length());
		String contenticon = SysProperty.getPrep("sysiconid_title");
		if(contenticon == null || contenticon.equals(""))
        	contenticon = "1";
		inPicSql.append("insert into news_contenttitle (contentid,contenttitle,contenticon,contenttext,contentsource,allow_scoring,newstype) values (");
		inPicSql.append(contentid+",");
		inPicSql.append(content_name+",");
		inPicSql.append(contenticon+",");
		inPicSql.append(content_detail+",");
		inPicSql.append(phone+",");
		inPicSql.append(one.getIsCallNow()+",");
		inPicSql.append("'ad')");
		em.createNativeQuery(inPicSql.toString()).executeUpdate();
		log.info(" insert Ads excute batch sql 2:" +inPicSql.toString());
		inPicSql.delete(0, inPicSql.length());
		String [] channelid=channelids.split(",");
		String tempSql="insert into news_extends_channel_title(channleid,cid,contentstatus,istest,isnew)VALUES(";
		int channleid=0;
		for(int i=0;i<channelid.length;i++)
        {
			sql="select channleid from news_extends_channel where channel_id='"+channelid[i]+"'";
			channleid=this.getOneInt();
			
			String tmp = tempSql+channleid+",(select LAST_INSERT_ID()),0,1,1)";
			em.createNativeQuery(tmp).executeUpdate();
			log.info(" insert Ads excute batch sql 3:" +tmp);
        }
		return true;
	}
	
	public boolean updateAds(NewsAdsVo one,String channelids)
	{
		BaseBean b = new BaseBean();
		ArrayList<String> sqllist = new ArrayList<String>();
		String contentid = b.ObjectToStringDB(one.getAdid());
		String ader = b.ObjectToStringDB(one.getAder());
		SimpleDateFormat simpledatetime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String content_name = b.ObjectToStringDB(one.getAdtitle());
		String content_detail = b.ObjectToStringDB(one.getAdtext());
		String pic_id = b.ObjectToStringDB(one.getAdpictureid());
		String content_pubdate = b.ObjectToStringDB(simpledatetime.format(one.getBegintime()));
		String deadline = b.ObjectToStringDB(simpledatetime.format(one.getEndtime()));
		String url = b.ObjectToStringDB(one.getAdurl()); 
		String standtime = b.ObjectToStringDB(one.getAdstandtime()); 
		String status = b.ObjectToStringDB(one.getAdstatus()); 
		String type = b.ObjectToStringDB(one.getAdtype()); 
		String order = b.ObjectToStringDB(one.getAdorder()); 
		String note = b.ObjectToStringDB(one.getNote()); 
		String phone = b.ObjectToStringDB(one.getPhone()); 
		StringBuffer inPicSql = new StringBuffer("");
//		inPicSql.append("ader="+ader+",");
//		inPicSql.append("adtitle="+content_name+",");
//		inPicSql.append("adtext="+content_detail+",");
//		inPicSql.append("adpictureid="+pic_id+",");
//		inPicSql.append("begintime="+content_pubdate+",");
//		inPicSql.append("createtime=now(),");
//		inPicSql.append("adurl="+url+",");
//		inPicSql.append("endtime="+deadline+",");
//		inPicSql.append("adstandtime="+standtime+",");
//		inPicSql.append("adtype='2',");
//		inPicSql.append("adorder="+order+",");
//		inPicSql.append("adstatus="+status+",");
//		inPicSql.append("note="+note+" where adid="+contentid);
//		sqllist.add(inPicSql.toString());
//		log.info(" update ADS excute batch sql 1:" +inPicSql.toString());
//		inPicSql.delete(0, inPicSql.length());
			
			Object cid = this.getSingleResult("select cid from NewsContenttitle where contentid="+contentid+" and newstype='ad'");
			String sql1="update news_ads set adtitle="+content_name+",adtext="+content_detail+",adpictureid="+pic_id+",adurl="+url+
					",adorder="+order+",ader="+ader+",endtime="+deadline+",begintime="+content_pubdate+",adstatus="+status+" where adid="+contentid;
			em.createNativeQuery(sql1).executeUpdate();
			inPicSql.append("update news_contenttitle set ");
			inPicSql.append("contenttitle="+content_name+",");
			inPicSql.append("contenttext="+content_detail+",contentsource="+phone+",allow_scoring="+one.getIsCallNow()+",updatetime=now() where contentid="+contentid);
			em.createNativeQuery(inPicSql.toString()).executeUpdate();
			log.info(" update ADS excute batch sql 2:" +inPicSql.toString());
			inPicSql.delete(0, inPicSql.length());
			//delete old channel content
			inPicSql.append("delete from news_extends_channel_title where cid="+cid+"");
			em.createNativeQuery(inPicSql.toString()).executeUpdate();
			log.info(" update ADS excute batch sql 3:" +inPicSql.toString());
			String [] channelid=channelids.split(",");
			String tempSql="insert into news_extends_channel_title(channleid,cid,contentstatus,istest,isnew)VALUES(";
		
//			this.init();
//			String sql3="select channleid from news_extends_channel where channel_id=?";
//			prep=conn.prepareStatement(sql3);
//			int channleid=0;
			for(String channelidOne : channelid)
	        {
				sql="select channleid from news_extends_channel where channel_id='"+channelidOne+"'";
				int channleid=this.getOneInt();
				String tmp = tempSql+channleid+"," + cid+",0,1,1)";
				em.createNativeQuery(tmp).executeUpdate();
				log.info(" updateAds excute batch sql 4:" +tmp);
	        }
			
		
		return true;
	}
	/*public boolean updateAdsStatus(String contentid){
		try {
	    Object cid = this.getSingleResult("select cid from NewsContenttitle where contentid='"+contentid+"' and newstype='ad'");
		ArrayList<String> sqlList = new ArrayList<String>();
		String sql = "update news_ads set adstatus='auditing' where adid ='"+contentid+"'";
		sqlList.add(sql);
		sql = "update news_extends_channel_title set contentstatus=0 where cid="+cid+"";
		sqlList.add(sql);
			return this.execTransaction(sqlList);
		} catch (Exception e) {
			log.info(" disable ads fail !!!" +e.getMessage());
			e.printStackTrace();
			return false;
		}
	}*/
	public boolean disableAds(String contentid)
	{
		String cidstr = this.getCidStrForContentidGLobal(contentid);
		ArrayList<String> sqlList = new ArrayList<String>();
		String sql = "update news_ads set adstatus='disable' where adid in ("+contentid+")";
		sqlList.add(sql);
		String[]  cid_arys=cidstr.split(",");
		for(String cid:cid_arys){
			sql = "update news_extends_channel_title set contentstatus=3 where cid="+cid+"";
			sqlList.add(sql);
		}
		try {
			return this.execTransaction(sqlList);
		} catch (Exception e) {
			log.info(" disable ads fail !!!" +e.getMessage());
			e.printStackTrace();
			return false;
		}
	}
	
	public boolean deleteAds(String contentid) {
		try {
			Object cid = this.getSingleResult("select cid from NewsContenttitle where contentid='"+contentid+"' and newstype='ad'");
			//ArrayList<String> ridList = this.queryALLResultSet("select rid from news_contenresource where cid="+cid);
			sql="select rid from news_contenresource where cid="+cid;
			ArrayList<Integer> ridList=(ArrayList<Integer>) em.createNativeQuery(sql).getResultList();
			String ridstr = "";
			for(Integer one : ridList)
			{
				ridstr+="'"+one+"',";
			}
			if(!"".equals(ridstr)){
				ridstr=ridstr.substring(0, ridstr.length()-1);
	    	}
			ArrayList<String> sqlList = new ArrayList<String>();
			String deleteSql = "delete from news_ads where adid ='"+contentid+"'";
			sqlList.add(deleteSql);
			deleteSql = "delete from news_extends_channel_title where cid ="+cid;
			sqlList.add(deleteSql);
			/*DataMap hasMap=this.queryOneRow("select nr.fullpath,nr.newformat from news_resources nr,news_contenresource ncr " +
			"where ncr.cid="+cid+"");
			deleteSql = "insert into t_resourcedelete (url,format) values('"+hasMap.getMapData("fullpath")+"','"+hasMap.getMapData("newformat")+"')";
			sqlList.add(deleteSql);	*/
			sql="select nr.fullpath,nr.newformat from news_resources nr,news_contenresource ncr " +
			"where ncr.cid="+cid+"";
			List<Object[]> temp=this.em.createNativeQuery(sql).getResultList();
			if(temp.size()>0){
				Object[] o=temp.get(0);
				deleteSql = "insert into t_resourcedelete (url,format) values('"+o[0]+"','"+o[1]+"')";
				sqlList.add(deleteSql);
			}
			
			String[] rid_arys=ridstr.split(",");
			for(String rid:rid_arys){
				rid=rid.substring(1,rid.length()-1);
				deleteSql = "delete from news_resources where rid="+rid+"";
				sqlList.add(deleteSql);
			}
			deleteSql = "delete from news_contenresource where cid="+cid;
			sqlList.add(deleteSql);
			deleteSql = "delete from news_contenttitle where cid="+cid;
			sqlList.add(deleteSql);
		
			return this.execTransaction(sqlList);
		} catch (Exception e) {
			log.info(" deleteAds fail !!!" +e.getMessage());
			e.printStackTrace();
			return false;
		}
	}
	
	public boolean subAdsAudit(String content_id_list)
	{
		String sql = "update news_ads set adstatus='auditing' where adid in ("+content_id_list+")";
		try {
			log.info(" subAudit excute sql :" +sql);
            return this.execUpdate(sql);
        } catch (Exception e) {
        	log.info(" subAdsAudit fail !!!" +e.getMessage());
            return false;
        }
	}
	
	//审核未通过
	public boolean unpassAds(String content_id_list)
	{
			//从复选框取得contentidlist
			String[] adids=content_id_list.split(",");
			for(String adid:adids){
				sql = "update news_ads set adstatus='unpass' where adid="+adid+"";
				log.info(" unpassAds excute sql:" +sql);
				em.createNativeQuery(sql).executeUpdate();
			}
		
		return true;
	}
	
	//广告截至时间是否有小于当前时间的（小于当前的）
	public boolean checkEndtimeBeforeNow(String content_id_list)
	{
		sql = "SELECT adid FROM news_ads WHERE adid IN("+content_id_list+") AND endtime < NOW()";
		log.info(" checkEndtimeBeforeNow:" +sql);
		try {
			List<Integer> lll=em.createNativeQuery(sql).getResultList();
			if(lll.size()>0){
				return true;
			}else{
				return false;
			}
		} catch (Exception e) {
			log.info(" checkEndtimeBeforeNow fail !!!" +e.getMessage());
			e.printStackTrace();
			return false;
		}
		
	}
	
	//审核通过
	public boolean auditAds(String content_id_list)
	{
			//从复选框取得contentidlist
			String[] adids=content_id_list.split(",");
			int cid=0;
			for(String adid:adids){
				sql = "update news_ads set adstatus='pass' where adid="+adid+"";
				log.info(" auditAds UPDATE news_ads Sql:" +sql);
				em.createNativeQuery(sql).executeUpdate();
				
				sql = "SELECT cid FROM news_contenttitle where contentid='"+adid+"' and newstype = 'ad'";
				cid=getOneInt();
				sql="update news_extends_channel_title set contentstatus=5 where cid ="+cid+"";
				log.info(" auditAds UPDATE news_extends_channel_title Sql:" +sql);
				em.createNativeQuery(sql).executeUpdate();
			}
		
		return true;
	}
	public boolean deleteAdsThumFile(String contentid)
	{
		try {
			Object cid = this.getSingleResult("select cid from NewsContenttitle where contentid='"+contentid+"' and newstype='ad'");
			String contenticon = SysProperty.getPrep("sysiconid_title");
			if(contenticon == null || contenticon.equals(""))
	        	contenticon = "1";
			//modify to update ad status
			ArrayList<String> sqlList = new ArrayList<String>();
			String sql = "update news_contenttitle set contenticon="+contenticon+" where contentid="+contentid+" and newstype='ad'";
			log.info(" deleteAdsThumFile excute update contenticon sql:" +sql);
			sqlList.add(sql);
			sql = "update news_ads set adstatus='auditing' where adid ='"+contentid+"'";
			log.info(" deleteAdsThumFile excute update news_ads adstatus sql:" +sql);
			sqlList.add(sql);
			sql = "update news_extends_channel_title set contentstatus=0 where cid="+cid+"";
			log.info(" deleteAdsThumFile excute update news_extends_channel_title contentstatus sql:" +sql);
			sqlList.add(sql);
		
			return this.execTransaction(sqlList);
		} catch (Exception e) {
			log.info(" deletePicFile fail !!!" +e.getMessage());
			e.printStackTrace();
			return false;
		}
	}
	/*public boolean insertAdsthum(NewsResources newsResources,String contentid)
	{
		ArrayList<String> sqlList = new ArrayList<String>();
        String sql = "insert into news_resources (useragents,name,resourcetype,url,size,rformat,spcode,newformat,fullpath) values " +
        		"('"+newsResources.getUseragents()+"','"+newsResources.getName()+"',"+
			newsResources.getResourcetype()+",'"+newsResources.getUrl()+"',"+newsResources.getSize()+",'"+newsResources.getRformat()+"'," +
				"'"+newsResources.getSpcode()+"','"+newsResources.getNewformat()+"','"+newsResources.getFullpath()+"')";
        sqlList.add(sql);
        log.info(" insert Ads excute batch sql 1:" +sql);
		sql = "update news_contenttitle set contenticon=(select LAST_INSERT_ID()) where contentid='"+contentid+"' and newstype='ad'";
		sqlList.add(sql);
		log.info(" insertAds excute batch sql 2:" +sql);
		try {
			return this.execTransaction(sqlList);
		} catch (Exception e) {
			log.info(" insert ads fail !!!" +e.getMessage());
			e.printStackTrace();
			return false;
		}
	}*/
	
	/*public boolean insertAdsResource(NewsResources newsResources,String contentid)
	{
		try {
			Object cid = this.getSingleResult("select cid from NewsContenttitle where contentid='"+contentid+"' and newstype='ad'");
			ArrayList<String> sqlList = new ArrayList<String>();
	        String sql = "insert into news_resources (useragents,name,resourcetype,url,size,rformat,spcode,newformat,fullpath) values " +
	        		"('"+newsResources.getUseragents()+"','"+newsResources.getName()+"',"+
				newsResources.getResourcetype()+",'"+newsResources.getUrl()+"',"+newsResources.getSize()+",'"+newsResources.getRformat()+"'," +
					"'"+newsResources.getSpcode()+"','"+newsResources.getNewformat()+"','"+newsResources.getFullpath()+"')";
	        sqlList.add(sql);
	        log.info(" insert Ads excute batch sql 1:" +sql);
			sql = "insert into news_contenresource (rid,cid) values ((select LAST_INSERT_ID()),"+cid+")";
			sqlList.add(sql);
			log.info(" insert Ads  excute batch sql 2:" +sql);
		
			return this.execTransaction(sqlList);
		} catch (Exception e) {
			log.info(" insert ads fail !!!" +e.getMessage());
			e.printStackTrace();
			return false;
		}
	}*/
	
	public List<String> getThumByContentid(String contentid)
	{
		sql = "SELECT nr.useragents,nr.newformat,nr.fullpath,nr.size,nc.contenticon FROM news_resources nr,news_contenttitle nc " +
				"where nc.contentid='"+contentid+"'  AND nc.contenticon=nr.rid AND nc.newstype='ad' ";
		log.info(" getResFullpathByContentid excute sql:" +sql);
		List<String> result = null;
		try {
			List<Object[]>tmpList =  em.createNativeQuery(sql).getResultList();
			if(tmpList!=null && tmpList.size()>0)
			{
				result = new ArrayList<String>();
				for(Object[] ss:tmpList){
					String fullpath = (String)ss[2];
					String newFormat = (String)ss[1];
					String size = (ss[3]==null?"":ss[3].toString());
					String contenticon =(ss[3]==null?"":ss[4].toString());
					fullpath = fullpath.substring(0,fullpath.indexOf("."))+"."+newFormat+"|"+size+"@@"+contenticon;
					result.add(fullpath);
				}
			}
			return result;
		} catch (Exception e) {
			log.info(" getResFullpathByContentid fail !!!" +e.getMessage());
			e.printStackTrace();
			return null;
		}
		
	}
	
	
	public List<String> getResFullpathByContentid(String contentid)
	{
		sql = "select nr.useragents,nr.newformat,nr.fullpath,nr.size from news_resources nr,news_contenttitle nc,news_contenresource ncr " +
				"where nc.contentid='"+contentid+"' and nc.cid=ncr.cid and nr.rid=ncr.rid  and nc.newstype='ad' ";
		log.info(" getResFullpathByContentid excute sql:" +sql);
		List<String> result = null;
		try {
			List<Object[]>tmpList =  em.createNativeQuery(sql).getResultList();
			if(tmpList!=null && tmpList.size()>0)
			{
				result = new ArrayList<String>();
				for(Object[] ss:tmpList){
					String fullpath = (String)ss[2];
					String newFormat = (String)ss[1];
					String size = (ss[3]==null?"":ss[3].toString());
					fullpath = fullpath.substring(0,fullpath.indexOf("."))+"."+newFormat+"|"+size;
					result.add(fullpath);
				}
			}
			return result;
		} catch (Exception e) {
			log.info(" getResFullpathByContentid fail !!!" +e.getMessage());
			e.printStackTrace();
			return null;
		}
	}
	
	//未选中的（编辑时显示在左侧的），已加权限
	public ArrayList findNotChooseChannel(String content_id, DataMap hashMap) {
		Object roleId = hashMap.get("role_id");
		Object userId = hashMap.get("user_id");
		String userids = (String)hashMap.get("userids");
		//root
		String findSql = "select tc.channel_id,tc.channel_name from t_channels tc WHERE 1=1 " +
				//will open
				" and status='"+BookConfig.channel_status_enable+"' " +
				" and (channel_type='"+BookConfig.channel_type_ad+"' or channel_type='"+BookConfig.channel_type_scrollbar+"' or channel_type='"+BookConfig.channel_type_hdnews+"') " +
				" and (tc.function_name='"+BookConfig.channel_last+"' OR tc.function_name='"+BookConfig.channel_song+"') ";
		//normal user
		if(roleId != null && !roleId.equals(""))
        { 
			findSql = "select tc.channel_id,tc.channel_name from t_channels tc,t_user_channels uc WHERE tc.channel_id=uc.channel_id " +
            		" and status='"+BookConfig.channel_status_enable+"'" +
        			" and (channel_type='"+BookConfig.channel_type_ad+"' or channel_type='"+BookConfig.channel_type_scrollbar+"' or channel_type='"+BookConfig.channel_type_hdnews+"') " +
            		" and (function_name='"+BookConfig.channel_last+"' OR function_name='"+BookConfig.channel_song+"')  " +
            		" and uc.employee_id=(SELECT employee_id FROM t_user where user_id='" + userId + "')";
        }else if(userids!=null)
        {
			findSql = "select DISTINCT tc.channel_id,tc.channel_name from t_channels tc,t_user_channels uc WHERE tc.channel_id=uc.channel_id " +
		    		" and status='"+BookConfig.channel_status_enable+"'" +
					" and (channel_type='"+BookConfig.channel_type_ad+"' or channel_type='"+BookConfig.channel_type_scrollbar+"' or channel_type='"+BookConfig.channel_type_hdnews+"') " +
		    		" and (function_name='"+BookConfig.channel_last+"' OR function_name='"+BookConfig.channel_song+"')  " +
		    		" and uc.employee_id in (SELECT employee_id FROM t_user where user_id in (" + userids + "))";
        }
		findSql = findSql + " and tc.channel_id not in (select tc.channel_id from t_channels tc,news_extends_channel nec," +
				"news_extends_channel_title nct,news_contenttitle nc where nc.contentid='"+content_id+"' and nc.cid=nct.cid and " +
						"nec.channel_id=tc.channel_id and nec.channleid=nct.channleid )";
		try {
			log.info("findNotChooseChannel sql: "+findSql);
			return this.queryALLResultSet(findSql.toString());
		} catch (Exception e) {
			log.info(" findNotChooseChannel fail !!!" +e.getMessage());
			return null;
		}
	}
	
	public ArrayList findSelectChannelsById(String content_id) {
		StringBuffer findSql = new StringBuffer("");
		findSql.append("select tc.channel_id,tc.channel_name from t_channels tc,news_extends_channel nec,news_extends_channel_title nct,news_contenttitle nc where ");
		findSql.append(" nc.contentid='" + content_id + "'");
		findSql.append(" and nc.cid=nct.cid ");
		findSql.append(" and nec.channel_id=tc.channel_id ");
		findSql.append(" and nec.channleid=nct.channleid ");
		//will open
		findSql.append(" AND (tc.function_name='"+BookConfig.channel_last+"' OR tc.function_name='"+BookConfig.channel_song+"') and (tc.channel_type='"+BookConfig.channel_type_ad+"' or tc.channel_type='"+BookConfig.channel_type_scrollbar+"' or channel_type='"+BookConfig.channel_type_hdnews+"')");
        try {
			return this.queryALLResultSet(findSql.toString());
		} catch (Exception e) {
			log.info(" findSelectChannelsById fail !!!" +e.getMessage());
            return null;
		}
	}
	
	public boolean deleteAdsFile(String filename,String contentid)
	{
		try {
		Object cid = this.getSingleResult("select cid from NewsContenttitle where contentid='"+contentid+"' and newstype='ad'");
		Integer rid = findPicidByFilename(filename);
		ArrayList<String> sqlList = new ArrayList<String>();
		/*DataMap hasMap=this.queryOneRow("select nr.fullpath,nr.newformat,nr.useragents from news_resources nr where nr.rid="+rid+"");
		String sql = "insert into t_resourcedelete (url,format,type) values('"+hasMap.getMapData("fullpath")+"','"+hasMap.getMapData("newformat")+"','"+hasMap.getMapData("useragents")+"')";
		sqlList.add(sql);*/
		sql="select nr.fullpath,nr.newformat,nr.useragents from news_resources nr where nr.rid="+rid+"";
		List<Object[]> temp=this.em.createNativeQuery(sql).getResultList();
		if(temp.size()>0){
			Object[] o=temp.get(0);
			sql = "insert into t_resourcedelete (url,format,type) values('"+o[0]+"','"+o[1]+"','"+o[2]+"')";
			sqlList.add(sql);
		}
		log.info(" deletePicFile excute batch sql 1:" +sql);
		sql = "delete from news_contenresource where rid=" + rid + " and cid="+cid;
		sqlList.add(sql);
		log.info(" deletePicFile excute batch sql 2:" +sql);
		sql = "delete from news_resources where rid=" + rid;
		sqlList.add(sql);
		log.info(" deletePicFile excute batch sql 3:" +sql);
		//add for update ad status
		sql = "update news_ads set adstatus='auditing' where adid ='"+contentid+"'";
		sqlList.add(sql);
		sql = "update news_extends_channel_title set contentstatus=0 where cid=" +cid;
		sqlList.add(sql);
		
			return this.execTransaction(sqlList);
		} catch (Exception e) {
			log.info(" deletePicFile fail !!!" +e.getMessage());
			e.printStackTrace();
			return false;
		}
	}
	
	public List getChannelsbyAds(String contentid)
	{
		String sql = "select tc.channel_id,tc.channel_name from news_contenttitle nc,t_channels tc,news_extends_channel_title nect,news_extends_channel nec " +
		"where nc.contentid='"+contentid+"' and nc.cid=nect.cid and nect.channleid=nec.channleid and tc.channel_id=nec.channel_id and nc.newstype='ad'";
		try {
			return this.queryALLResultSet(sql);
		} catch (Exception e) {
			log.info(" getChannelsbyPicture fail !!!" +e.getMessage());
			return null;
		}
	}
	
	
	/**
	 * 根据QuartzJob调度器更新NewsExtendsChannelTitle.Contentstatus
	 *//*
	public String updateNctContentstatusByJob(String jobName){
	    String sql="select channleid from news_extends_channel where updatetimer='"+jobName+"' and channleid in " +
	    		"(SELECT DISTINCT(nct.channleid)  FROM news_extends_channel_title AS nct, news_ads AS ad ,news_contenttitle AS nc " +
	    		"WHERE ad.adtype=2 AND ad.begintime <=NOW() AND ad.endtime >=NOW() AND ad.adid=nc.contentid AND nc.cid=nct.cid AND " +
	    		"nct.istest=1 AND nct.contentstatus=5 )";
	    //要更新的channleid集合  contentstatus=2
	    List<DataMap> list=null;
	    try {
			list=this.queryALLResultSet(sql);
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		
		sql="select channleid from news_extends_channel where updatetimer='"+jobName+"' and channleid in (SELECT DISTINCT(nct.channleid) " +
				"FROM news_extends_channel_title AS nct, news_ads AS ad ,news_contenttitle AS nc WHERE ad.adtype=2 AND  ad.endtime <=NOW() " +
				"AND ad.adid=nc.contentid AND nc.cid=nct.cid)";
	    //要更新的channleid集合3  contentstatus=1,更新状态为3
	    List<DataMap> list3=null;
	    try {
	    	list3=this.queryALLResultSet(sql);
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		
		sql="select channleid from news_extends_channel where updatetimer='"+jobName+"' and channleid in (select channleid from news_extends_channel_title where contentstatus=3)";
	    //要更新的channleid集合3  contentstatus=3,更新状态为4
	    List<DataMap> list4=null;
	    try {
	    	list4=this.queryALLResultSet(sql);
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		
		//要更新的频道，频道内容下没有更新的内容 isnew=2 为旧的。
		for(int i=0;i<list.size();i++){
	    	int channleid=Integer.parseInt(list.get(i).getMapData("channleid"));
	    	 sql="update news_extends_channel_title  set isnew=2 where istest=1 and contentstatus=1 and " +
    		"channleid ="+channleid ;     		
         try {
    	
    	     log.info("job: "+ jobName + " excute sql: "+sql);
    	     this.execUpdateRicode(sql);
	         } catch (Exception e) {
	          	e.printStackTrace();
	         } 
	    }
		
		//删除频道绑定的已过期广告
	    	 sql="DELETE FROM news_extends_channel_ads WHERE adid IN (SELECT ad.adid FROM news_extends_channel_title AS nct, " +
	    	 		"news_ads AS ad ,news_contenttitle AS nc WHERE ad.adtype=2 AND  ad.endtime <=NOW() AND ad.adid=nc.contentid " +
	    	 		"AND nc.cid=nct.cid )";     		
         try {
    	
    	     log.info("删除普通频道绑定的已过期广告job: "+ jobName + " excute sql: "+sql);
    	     this.execUpdateRicode(sql);
	         } catch (Exception e) {
	          	e.printStackTrace();
	         } 
		
		//删除一级频道绑定的已过期广告
	    	 sql="DELETE FROM news_extends_firstchannel_ads WHERE adid IN (SELECT ad.adid FROM news_extends_channel_title AS nct, " +
	    	 		"news_ads AS ad ,news_contenttitle AS nc WHERE ad.adtype=2 AND  ad.endtime <=NOW() AND ad.adid=nc.contentid AND " +
	    	 		"nc.cid=nct.cid )";     		
         try {
    	
    	     log.info("删除一级频道绑定的已过期广告job:  "+ jobName + " excute sql: "+sql);
    	     this.execUpdateRicode(sql);
	         } catch (Exception e) {
	          	e.printStackTrace();
	         } 
		
		  String channelidlist="";
		  Set<String> channelidSet=new HashSet<String>();
    	  for(int i=0;i<list.size();i++){
	    	int channleid=Integer.parseInt(list.get(i).getMapData("channleid"));
	    	
	    	 sql="UPDATE  news_extends_channel_title AS nec ,news_ads AS ad ,news_contenttitle AS ncc SET nec.contentstatus=1," +
	    	 		"nec.isnew=1 WHERE nec.channleid ="+channleid +"  AND nec.cid = ncc.cid AND ad.adtype=2 AND ad.begintime <=NOW() " +
	    	 				"AND ad.endtime >=NOW() AND ad.adid=ncc.contentid AND nec.istest=1 AND nec.contentstatus=5";     		
	    	 
	    	 log.info("job: "+ jobName + " excute sql: "+sql);
	    	 try {
	    		 if(this.execUpdateRicode(sql)>0){
	    			 channelidSet.add(list.get(i).getMapData("channleid"));
	   	         }
	    	 }catch (Exception e) {
		          	e.printStackTrace();
		     } 
	    }
    	  
    	for(int i=0;i<list3.size();i++){
  	    	int channleid=Integer.parseInt(list3.get(i).getMapData("channleid"));
  	    	 //时间过期更新为4   其他状态 
  	    	 sql="UPDATE news_extends_channel_title AS nec ,news_ads AS ad ,news_contenttitle AS ncc SET nec.contentstatus=4," +
  	    	 	"ad.adstatus='disable',nec.isnew=1 WHERE nec.contentstatus=1 and nec.channleid ="+channleid +"  AND nec.cid = ncc.cid AND ad.adtype=2 " +
				"AND ad.endtime <=NOW() AND ad.adid=ncc.contentid"; 
  	    	  
  	    	 try {
  	    		 if(this.execUpdateRicode(sql)>0){
  	    			 channelidSet.add(list3.get(i).getMapData("channleid"));
  	   	         }
  	    	 }catch (Exception e) {
  		          	e.printStackTrace();
  		     } 
  	    }
    	
    	for(int i=0;i<list4.size();i++){
  	    	int channleid=Integer.parseInt(list4.get(i).getMapData("channleid"));
  	    	 //3 下线更新为 4其它状态 
  	    	 sql="update news_extends_channel_title  set contentstatus=4 where contentstatus=3 and " +
  	    		"channleid ="+channleid ;   
  	    	 try {
  	    		 if(this.execUpdateRicode(sql)>0){
  	    			 channelidSet.add(list4.get(i).getMapData("channleid"));
  	   	         }
  	    	 }catch (Exception e) {
  		          	e.printStackTrace();
  		     } 
  	    }
    	for(Iterator<String> it=channelidSet.iterator();it.hasNext();){
  		 	if("".equals(channelidlist)){
  		 		channelidlist=""+it.next();
    	   		}else{
    	   			channelidlist+=","+it.next();
    	   		}
  	      }
	    return channelidlist;
	} */

    //add 1119 select channel update
    public DataMap buildLastChannelMap()
    {
    	String sql = "SELECT channel_id,channel_name,function_name,previous_id FROM t_channels t";
    	HashMap<String,String> childIdAndPreiousId = new HashMap<String,String>();
    	HashMap<String,String> idAndName = new HashMap<String,String>();
    	DataMap result = new DataMap();
    	List chList = null;
    	try {
			chList = this.queryALLResultSet(sql);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
		//首先建立两个map准备数据
		for(int i=0;i<chList.size();i++)
		{
			HashMap hashMap = (HashMap)chList.get(i);
			String channel_id = (String)hashMap.get("channel_id");
			String chName = (String)hashMap.get("channel_name");
			String fnName = (String)hashMap.get("function_name");
			String previous_id = (String)hashMap.get("previous_id");
			//先将id和name装入map
			idAndName.put(channel_id, chName);
			//channel如果是normal或者first,就装入map,key是channel_id,value是
			if(fnName.equals(BookConfig.channel_first) || fnName.equals(BookConfig.channel_normal))
			{
				childIdAndPreiousId.put(channel_id, previous_id);
			}
		}
		//build map,key:channleid value:previousid+name
		for(int i=0;i<chList.size();i++)
		{
			HashMap hashMap = (HashMap)chList.get(i);
			String channel_id = (String)hashMap.get("channel_id");
			String chName = (String)hashMap.get("channel_name");
			String fnName = (String)hashMap.get("function_name");
			String previous_id = (String)hashMap.get("previous_id");
			//如果是normal或者first,就装入map,key是channel_id,value是
			if(fnName.equals(BookConfig.channel_last) || fnName.equals(BookConfig.channel_song))
			{
				String previousChName = idAndName.get(previous_id);
				chName = chName+"="+previousChName;
				chName = getValue(childIdAndPreiousId,idAndName,previous_id,chName);
				//最上一级的频道名称必然是news,把news过滤掉
				chName = chName.substring(0,chName.lastIndexOf("="));
				String[] tmp = chName.split("=");
				String value = "";
				for(int j=tmp.length-1;j>=0;j--)
				{
					value=value+tmp[j]+"--";
				}
				value = value.substring(0,value.length()-2);
				result.put(channel_id, value);
			}
		}
    	return result;
    }
    
    private String getValue(HashMap<String,String> idmap,HashMap<String,String> namemap,String key,String result)
    {
    	String parentid = idmap.get(key);
    	String parentname = namemap.get(parentid);
    	if((key != null && parentid!=null) && !parentid.equals(key))
    	{
    		result = result+"="+parentname;
    		return getValue(idmap,namemap,parentid,result);
    	}
    	else
    	{
    		return result;
    	}
    }
    //add for multi catalog
    public ArrayList getChannelPlatform()
    {
    	ArrayList result = new ArrayList();
    	//1 取得所有生效的catalog对应的catalogchannelid
    	String sql = "SELECT ncc.channelid,ncp.mplatform,ncp.magent,ncp.mserialnum,ncp.mlocale,ncp.catlogid" +
    			" FROM news_catlog nc left join news_catlog_platform ncp on ncp.catlogid=nc.catlogid," +
    			"news_catlog_channel ncc where nc.isnowpublish in (1,2) and nc.catlogid=ncc.catlogid";
    	ArrayList catalogChannelidAndPlatformList = new ArrayList();
    	try {
    		catalogChannelidAndPlatformList = this.queryALLResultSet(sql);
    		if(catalogChannelidAndPlatformList.size()>0)
    		{
	    		for(int i=0;i<catalogChannelidAndPlatformList.size();i++)
	    		{
	    			DataMap lastChannelAndPlatform = new DataMap();
	    			HashMap hashmap = (HashMap)catalogChannelidAndPlatformList.get(i);
	    			String catalogChannelid = (String)hashmap.get("channelid");
	    			String platforminfo = InterUtil.rb.getString("src.gameplatform")+hashmap.get("mplatform")+"."+
	    			InterUtil.rb.getString("src.gamedistributor")+hashmap.get("magent")+"."+InterUtil.rb.getString("src.clientsn")+
	    			hashmap.get("mserialnum")+"."+InterUtil.rb.getString("src.languagearea")+hashmap.get("mlocale");
	    			sql = "SELECT nc.channel_id FROM news_buttons nb,news_extends_firstchannel_buttons nfb,news_contenttype nc where " +
	    					"nfb.channelid="+catalogChannelid+" and nc.newscontenttype=nb.buttoncontenttype and nfb.buttonid=nb.buttonid";
	    			ArrayList tchannelIdList = this.queryALLResultSet(sql);
	    			if(tchannelIdList.size()>0)
	    			{
	    				//首先要判断结果集里的channel是否最后一级
	    				for(int j=0;j<tchannelIdList.size();j++)
	    				{
	    					DataMap tmpMap = (DataMap)tchannelIdList.get(j);
	    					String tch_id = tmpMap.getMapData("channel_id");
	    					if(tch_id == null || tch_id.equals(""))
	    						continue;
	    					sql = "select function_name from t_channels where channel_id='"+tch_id+"'";
	    					String functionname = this.queryOne(sql);
	    					//if最后一级 放到map里 key是最后一级的id value是platforminfo
	    					if(functionname.toUpperCase().equals("LAST") || functionname.toUpperCase().equals("CHANNELSONG"))
	    						lastChannelAndPlatform.put(tch_id, platforminfo);
	    					//不是 递归查询
	    					else
	    						buildLastChannelAndPlatform(tch_id,platforminfo,lastChannelAndPlatform);
	    				}
	    			}
	    			result.add(lastChannelAndPlatform);
	    		}
    		}
		} catch (Exception e) {
			e.printStackTrace();
		}
    	return result;
    }
    
    private void buildLastChannelAndPlatform(String tch_id,String platforminfo,DataMap lastChannelAndPlatform)
    {
    	String sql = "SELECT channel_id,function_name FROM t_channels where previous_id='"+tch_id+"'";
    	try {
			ArrayList chList = this.queryALLResultSet(sql);
			for(int i=0;i<chList.size();i++)
			{
				HashMap hashMap = (HashMap)chList.get(i);
				String fnName = (String)hashMap.get("function_name");
				String channel_id = (String)hashMap.get("channel_id");
				if(fnName.toUpperCase().equals("LAST") || fnName.toUpperCase().equals("CHANNELSONG"))
					lastChannelAndPlatform.put(channel_id, platforminfo);
				else
					buildLastChannelAndPlatform(channel_id,platforminfo,lastChannelAndPlatform);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
    }

	public boolean uploadads(String contentid, NewsResources adsRes,
			List<NewsResources> adsRessList,int type) {
		//type,1:上传，2：重新上传
			//缩略图
			if(adsRes!=null){
			    em.persist(adsRes);
			    log.info(" insertAdsthum excute batch sql 1:" +sql);
				sql = "update news_contenttitle set contenticon="+adsRes.getRid()+" where contentid='"+contentid+"' and newstype='ad'";
				em.createNativeQuery(sql).executeUpdate();
				log.info(" insertAdsthum excute batch sql 2:" +sql);
			}
			Object cid = this.getSingleResult("select cid from NewsContenttitle where contentid='"+contentid+"' and newstype='ad'");
			//广告图片
			for(NewsResources adsRess:adsRessList){
				em.persist(adsRess);
		        log.info(" insert Ads excute batch sql 1:" +sql);
				sql = "insert into news_contenresource (rid,cid) values ("+adsRess.getRid()+","+cid+")";
				em.createNativeQuery(sql).executeUpdate();
				log.info(" insert Ads  excute batch sql 2:" +sql);
			}
			if(type==2){
				sql = "update news_ads set adstatus='auditing' where adid ='"+contentid+"'";
				em.createNativeQuery(sql).executeUpdate();
				sql = "update news_extends_channel_title set contentstatus=0 where cid="+cid+"";
				em.createNativeQuery(sql).executeUpdate();
			}
		
		return true;
		
	}
	
}
